package org.example;

import java.util.Scanner;

public class algorithm_Demo2 {
    //分块查找
    public static void main(String[] args) {
        int []arr={16,5,9,12,21,18,
                   32,23,37,26,45,34,
                   50,48,61,52,73,66};
        Block b1=new Block(21,0,5);
        Block b2=new Block(45,6,11);
        Block b3=new Block(73,12,17);
        Block[]blocksArr={b1,b2,b3};
        System.out.println("请输入要查找的数字：");
        int number=new Scanner(System.in).nextInt();
        int index=getIntdex(blocksArr,arr,number);
        System.out.println(index);
    }

    private static int getIntdex(Block[] blocksArr, int[] arr, int number) {
        int indexBlocks=findMax(blocksArr,number);
        if(indexBlocks==-1){
            return -1;
        }
        int startIndex=blocksArr[indexBlocks].getStartIndex();
        int endIndex=blocksArr[indexBlocks].getEndIndex();
        for (int i = startIndex; i <=endIndex; i++) {
            if(arr[i]==number){
                return i;
            }
        }
        return -1;
    }

    //找在哪个分块
    public static int findMax(Block[] blocksArr,int number) {
        for (int i = 0; i < blocksArr.length; i++) {
            if(number<=blocksArr[i].getMax()){
                return i;
            }
        }
        return -1;
    }

    static class Block{
        int max;
        int startIndex;
        int endIndex;

        public Block(int max, int startIndex, int endIndex) {
            this.max = max;
            this.startIndex = startIndex;
            this.endIndex = endIndex;
        }

        public int getMax() {
            return max;
        }

        public void setMax(int max) {
            this.max = max;
        }

        public int getStartIndex() {
            return startIndex;
        }

        public void setStartIndex(int startIndex) {
            this.startIndex = startIndex;
        }

        public int getEndIndex() {
            return endIndex;
        }

        public void setEndIndex(int endIndex) {
            this.endIndex = endIndex;
        }
    }
}
